package com.longfa.ojbackendjudgeservice.service;

import cn.hutool.json.JSONUtil;
import com.longfa.ojbackendcommon.common.ErrorCode;
import com.longfa.ojbackendcommon.exception.BusinessException;
import com.longfa.ojbackendjudgeservice.codesandbox.CodeSandbox;
import com.longfa.ojbackendjudgeservice.codesandbox.CodeSandboxFactory;
import com.longfa.ojbackendjudgeservice.codesandbox.CodeSandboxProxy;
import com.longfa.ojbackendjudgeservice.strategy.JudgeContext;
import com.longfa.ojbackendjudgeservice.strategy.JudgeManager;
import com.longfa.ojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.longfa.ojbackendmodel.model.codesandbox.ExecuteCodeResponse;
import com.longfa.ojbackendmodel.model.codesandbox.JudgeInfo;
import com.longfa.ojbackendmodel.model.dto.question.JudgeCase;
import com.longfa.ojbackendmodel.model.entity.Question;
import com.longfa.ojbackendmodel.model.entity.QuestionSubmit;
import com.longfa.ojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.longfa.ojbackendserviceclient.service.QuestionFeignClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: JudgeServiceImpl
 * Package: com.fa.oj.judge
 * Description:
 *
 * @Author:
 * @Create: 2024/4/23 - 18:46
 * @Version: v1.0
 */
@Service
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private QuestionFeignClient questionFeignClient;

    @Resource
    private JudgeManager judgeManager;

    @Value("${code-sandbox.type:example}")
    private String type;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 1） 传入题目的提交id， 获取到对应的题目、提交信息（包含代码、编程语言）
        //1.1 根据题目提交id获取到题目提交信息
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        //1.2 获取题目
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeignClient.getQuestionById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        // 如果题目的判题状态不为等待中，说明题目已经在判题或判题完成，这样就不需要再进行判题
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目已经在判题或判题完成");
        }
        // 题目没有判题，就修改题目提交的状态
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目提交状态修改失败");
        }
        // 题目提交状态修改完成后，调用代码沙箱执行代码
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        // 这里的 judgeCaseStr有多个 judgeCase
        String judgeCaseStr = question.getJudgeCase();
        // 获取测试的输入用例
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        // 2） 调用沙箱，获取到执行结果
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .inputList(inputList)
                .code(code)
                .language(language)
                .build();
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        CodeSandboxProxy codeSandboxProxy = new CodeSandboxProxy(codeSandbox);
        ExecuteCodeResponse executeCodeResponse = codeSandboxProxy.executeCode(executeCodeRequest);
        List<String> outputListByResponse = executeCodeResponse.getOutputList();
        JudgeInfo judgeInfo = executeCodeResponse.getJudgeInfo();
        // 3） 根据沙箱的执行结果，设置题目的判题状态和信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(judgeInfo);
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputListByResponse);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);

        // 在这里根据 编程语言选择 判题策略
        JudgeInfo JudgeInfoResult = judgeManager.doJudge(judgeContext);
        // 修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(JudgeInfoResult));
        boolean result = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交更新失败");
        }
        QuestionSubmit questionSubmitResult = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        return questionSubmitResult;
    }
}
